package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Visitor;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 访客服务实现类
 */
@Service
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *如果上次登录时间存在，date（访客访问时间）>上次登录时间5条记录
     * @param lastLoginTimeLong
     * @param userId
     * @return
     */
    @Override
    public List<Visitor> queryVisitorsByDate(Long lastLoginTimeLong, Long userId) {
        Query query = new Query();
        //userid=xx and lastLoginTimeLong>='xxx'
        query.addCriteria(Criteria.where("userId").is(userId).and("date").gte(lastLoginTimeLong));
        query.limit(5);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitor.class);
    }

    /**
     * 如果上次登录时间不存在，从所有访客记录中查询5条记录
     * @param userId
     * @return
     */
    @Override
    public List<Visitor> queryVisitors(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.limit(5);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitor.class);
    }


    /**
     * 保存访客记录
     */
    @Override
    public void save(Visitor visitor) {
        visitor.setId(ObjectId.get());
        visitor.setDate(System.currentTimeMillis());
        mongoTemplate.save(visitor);
    }
}
